<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class TagController extends Controller
{
    // 标签列表
	public function tag_list()
	{
		$tags = DB::table('tags')->orderBy('tid','desc')->paginate(20);
		return view('admin/tag_list',['tags'=>$tags]); 
	}
	
	// 添加列表
	public function tag_add(Request $request)
	{
		if($request->isMethod('post')){
			$tname = $request->input('tname','','htmlspecialchars');
			if(empty($tname)) return redirect('/prompt')->with(['message'=>'标签名不能为空','url' =>'/admin/tag_add', 'jumpTime'=>3,'status'=>'error']);
			
			# 插入数据
			$res = DB::table('tags')->insert(['tname'=>$tname]);
			if($res){
				return redirect('tag_list');
			} else {
				return redirect('/prompt')->with(['message'=>'添加失败，请联系客服','url' =>'/admin/tag_add', 'jumpTime'=>3,'status'=>'error']);
			}
		}
		return view('admin/tag_add');
	}
	
	// 修改列表
	public function tag_edit(Request $request,$tid)
	{
		if(!preg_match('/^[1-9]\d*$/',$tid)) return redirect('/prompt')->with(['message'=>'参数错误','url' =>'/admin/tag_list', 'jumpTime'=>3,'status'=>'error']);
		# 查询内容
		$tag = DB::table('tags')->where('tid',$tid)->select('tname','tid')->first();
		if($request->isMethod('post')){
			$tname = $request->input('tname','','htmlspecialchars');
			if(empty($tname)) return redirect('/prompt')->with(['message'=>'内容不能为空','url' =>'/admin/tag_add', 'jumpTime'=>3,'status'=>'error']);
			
			# 更新数据
			$res = DB::table('tags')->where('tid',$tid)->update(['tname'=>$tname]);
			if($res){
				return redirect('tag_list');
			} else {
				return redirect('/prompt')->with(['message'=>'更新失败，请联系客服','url' =>'/admin/tag_edit/'.$tid, 'jumpTime'=>3,'status'=>'error']);
			}
		}
		return view('admin/tag_edit',['tag'=>$tag]);
	}
	
	// 删除列表
	public function tag_del(Request $request)
	{
		if($request->isMethod('post')){
			$tid = $request->input('tid');
			if(!preg_match('/^[1-9]\d*$/',$tid)) return redirect('/prompt')->with(['message'=>'参数错误','url' =>'/admin/tag_list', 'jumpTime'=>3,'status'=>'error']);
			
			# 删除数据
			$res = DB::table('tags')->where('tid',$tid)->delete();
			if($res){
				json_return(200,'删除成功');
			} else {
				json_return(1000,'删除失败');
			}
		}
	}
	
	
	
}
